package com.ahp.service.impl;

import java.util.List;
import java.util.Map;

import org.apache.struts2.ServletActionContext;

import com.ahp.bean.User;
import com.ahp.dao.UserDao;
import com.ahp.service.UserService;
import com.ahp.util.PageList;
import com.ahp.util.Pages;

public class UserServiceImpl implements UserService {
	
	private UserDao userDao;

	public UserDao getUserDao() {
		return userDao;
	}

	public void setUserDao(UserDao userDao) {
		this.userDao = userDao;
	}
	
	/* (non-Javadoc)
	 * @see com.ahp.service.UserService#getUser(java.lang.Integer)
	 */
	public User getUser(Integer id) {
		return userDao.getUser(id);
	}

	/* (non-Javadoc)
	 * @see com.ahp.service.UserService#saveUser(com.ahp.bean.User)
	 */
	public void saveUser(User user) {
		try {
			userDao.saveUser(user);
		} catch (Exception e) {
			// TODO: handle exception
		}
		Map<String,User> session = ServletActionContext.getContext().getSession();
		///if(User.USER_TYPE.equals(user.getType())){
			session.put(User.USER_SESSION, user);
		///}else {
		///	session.put(User.MANAGER_SESSION, user);
		//}
	}

	/* (non-Javadoc)
	 * @see com.ahp.service.UserService#updateUser(com.ahp.bean.User)
	 */
	public void updateUser(User user) {
		userDao.updateUser(user);
	}
	
	/* (non-Javadoc)
	 * @see com.ahp.service.UserService#login(java.lang.String, java.lang.String)
	 */
	public boolean login(String loginName, String password) {
		List<User> list = userDao.getUserByName(loginName);
		if(list.size() < 1){
			return false;
		}
		for (User user : list) {
			if(password.equals(user.getPassword())){
				Map<String,User> session = ServletActionContext.getContext().getSession();
				//if(User.USER_TYPE.equals(user.getType())){
					session.put(User.USER_SESSION, user);
				//}else {
				//	session.put(User.MANAGER_SESSION, user);
				//}
				return true;
			}
		}
		return false;
	}
	
	/* (non-Javadoc)
	 * @see com.ahp.service.UserService#listUser(com.ahp.util.Pages)
	 */
	public PageList listUser(Pages pages) {
		String hql = "from User u";
		return userDao.pageQuery(pages, hql);
	}
	
	/* (non-Javadoc)
	 * @see com.ahp.service.UserService#checkUser(com.ahp.bean.User)
	 */
	public boolean checkUser(User user) {
		List<User> list = userDao.getUserByName(user.getLoginName());
		if(list.size()>0){
			return true;
		}else{
			return false;
		}
	}
	
}
